package com.topisv.tms.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.Department;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.User;
import com.topisv.tms.repository.DepartmentDao;
import com.topisv.tms.repository.UserDao;
import com.topisv.tms.service.base.BaseService;

//Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional(readOnly = true)
public class DepartmentService extends BaseService{

	private DepartmentDao departmentDao;
	
	private UserDao userDao;

	public Department getDepartment(Long id) {
		return departmentDao.findOne(id);
	}

	@Transactional(readOnly = false)
	public void saveDepartment(Department entity) {
		departmentDao.save(entity);
	}

	@Transactional(readOnly = false)
	public void deleteDepartment(Long id) {
		departmentDao.delete(id);
	}

	public List<Department> getAllDepartment() {
		return (List<Department>) departmentDao.findAll();
	}
	
	
	public List<Map> getDepartmentTree()
	{
		List<Map> treeMap = new ArrayList<Map>();
		List<Department> departments = (List<Department>) departmentDao.findByStatus("1");
		String split = "";
		generateTree(split,"0",departments,treeMap);
		return treeMap;
		
	}
	
	public void generateTree(String split,String depintro ,List<Department> departments,List<Map> treeMap)
	{
		List<Department> departmentsTmp = new ArrayList<Department>();
		for(Department department : departments)
		{
			if(depintro.equals(department.getDepartment().getDeptintro()))
			{
				departmentsTmp.add(department);
			}
		}
		
		if(departmentsTmp.size() == 0)
		{
			return;
		}
		if(!"0".equals(depintro))
			split += "&nbsp;&nbsp;&nbsp;&nbsp;";
		for(Department department2 : departmentsTmp)
		{
				HashMap map = new HashMap();
				map.put(department2.getId(), split + department2.getDeptname());
				treeMap.add(map);
				generateTree(split,department2.getDeptintro(),departments,treeMap);
		}
	}
	/**
	 * 分页显示表内所有行.
	 */
	public Page<Department> getDepartment(QueryParamHolder paramHolder) {
		return findByJson(paramHolder, departmentDao, Department.class);
	}


	@Autowired
	public void setDepartmentDao(DepartmentDao departmentDao) {
		this.departmentDao = departmentDao;
	}

	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public List<User> findByDepartmentId(Long id) {
		return userDao.findByDepartmentId(id);
	}

	public List<Department> getSubDepartmentById(Long id) {
		return departmentDao.getSubDepartmentByid(id);
	}
}
